package com.wuzhun.wxmp.interceptor;

import com.alibaba.fastjson.JSON;
import com.wuzhun.wxmp.model.dto.OperateLogDTO;
import com.wuzhun.wxmp.service.AsyncService;
import com.wuzhun.wxmp.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 日志拦截器
 *
 * @author baolin
 * @date 2022/12/03 14:24 下午
 */
@Component
public class LogInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);

    @Resource
    private AsyncService asyncService;

    /**
     * 请求处理之后
     *
     * @param request
     * @param response
     * @param handler
     * @param exception
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
            throws Exception {
        OperateLogDTO dto = new OperateLogDTO();
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap != null && parameterMap.size() > 0) {
            String content = JSON.toJSONString(parameterMap);
            dto.setParams(content);
        }
        // ip
        dto.setIp(IpUtil.getIpAddress(request));
        // 请求接口设置
        String requestURI = request.getRequestURI();
        dto.setUrl(requestURI);
        Object returnCode = request.getSession().getAttribute("returnCode");
        if (returnCode != null) {
            dto.setReturnCode(returnCode.toString());
            request.getSession().setAttribute("returnCode", null);
        }
        asyncService.insertOperateLog(dto);
        HandlerInterceptor.super.afterCompletion(request, response, handler, exception);
    }

    /**
     * 请求处理之后调用
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }


    /**
     * 请求处理之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return true;
    }
}